package actions.generate.dialog;

import utils.CommonUtil;

import javax.swing.*;
import java.awt.*;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class LayoutChooseDialog extends JDialog {

    private final List<String> layoutNames;
    private final IOnConfirm onConfirmListener;

    public static void show(IOnConfirm onConfirmListener, List<String> layoutNames) {
        LayoutChooseDialog dialog = new LayoutChooseDialog(onConfirmListener, layoutNames);
        dialog.setLayout(new FlowLayout());
        CommonUtil.showDialog(dialog, "发现多个layout inflate，选择生成");
    }

    private LayoutChooseDialog(IOnConfirm onConfirmListener, List<String> layoutNames) {
        this.layoutNames = layoutNames;
        this.onConfirmListener = onConfirmListener;
        setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        generateRatios();
    }

    private void generateRatios() {
        ButtonGroup group = new ButtonGroup();

        boolean hasSel = false;
        for (String layout : layoutNames) {
            JPanel container = new JPanel();
            JRadioButton button = new JRadioButton(layout);
            if (!hasSel) {
                button.setSelected(true);
                hasSel = true;
            }
            group.add(button);
            container.add(button);
            add(container);
        }

        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {
            Enumeration<AbstractButton> buttonEnumeration = group.getElements();
            while (buttonEnumeration.hasMoreElements()) {
                JRadioButton jr = (JRadioButton) buttonEnumeration.nextElement();
                if (jr.isSelected()) {
                    if (onConfirmListener != null) {
                        onConfirmListener.onConfirm(jr.getText());
                    }
                    dispose();
                }
            }
        });

        JPanel container = new JPanel();
        container.add(confirmButton);
        add(container);
    }

    public interface IOnConfirm {
        void onConfirm(String layout);
    }

    public static void main(String[] args) {
        List<String> list = new LinkedList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("cccc");
        LayoutChooseDialog.show(System.out::println, list);
    }
}
